<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户详情</span>
          <div>
            <el-button type="primary" @click="editUser">编辑</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <div v-loading="loading" class="user-detail">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="avatar-section">
                <el-avatar :size="120" :src="userInfo.avatar || '/default-avatar.png'" />
                <div class="user-status">
                  <el-tag :type="userInfo.status === 'ACTIVE' ? 'success' : 'danger'">
                    {{ userInfo.status === 'ACTIVE' ? '正常' : '禁用' }}
                  </el-tag>
                </div>
              </div>
            </el-col>
            <el-col :span="18">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
                <el-descriptions-item label="昵称">{{ userInfo.nickname }}</el-descriptions-item>
                <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ userInfo.phone }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ getGenderText(userInfo.gender) }}</el-descriptions-item>
                <el-descriptions-item label="生日">{{ formatDate(userInfo.birthday) }}</el-descriptions-item>
                <el-descriptions-item label="用户类型">{{ getUserTypeText(userInfo.userType) }}</el-descriptions-item>
                <el-descriptions-item label="注册时间">{{ formatDateTime(userInfo.createTime) }}</el-descriptions-item>
                <el-descriptions-item label="最后登录">{{ formatDateTime(userInfo.lastLoginTime) }}</el-descriptions-item>
                <el-descriptions-item label="登录次数">{{ userInfo.loginCount || 0 }}</el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </div>

        <!-- 角色权限 -->
        <div class="detail-section">
          <h3>角色权限</h3>
          <div class="roles-section">
            <el-tag
              v-for="role in userInfo.roles"
              :key="role.id"
              type="primary"
              style="margin-right: 8px; margin-bottom: 8px;"
            >
              {{ role.name }}
            </el-tag>
          </div>
          <div class="permissions-section" style="margin-top: 16px;">
            <h4>权限列表</h4>
            <el-tree
              :data="permissions"
              :props="{ children: 'children', label: 'name' }"
              show-checkbox
              :default-checked-keys="userPermissions"
              node-key="id"
              :disabled="true"
            />
          </div>
        </div>

        <!-- 扩展信息 -->
        <div class="detail-section">
          <h3>扩展信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="学校/机构">{{ userInfo.organization || '未填写' }}</el-descriptions-item>
            <el-descriptions-item label="专业/部门">{{ userInfo.department || '未填写' }}</el-descriptions-item>
            <el-descriptions-item label="地址" :span="2">{{ userInfo.address || '未填写' }}</el-descriptions-item>
            <el-descriptions-item label="个人简介" :span="2">
              <div class="bio-content">{{ userInfo.bio || '未填写' }}</div>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 统计信息 -->
        <div class="detail-section">
          <h3>统计信息</h3>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-statistic title="学习课程" :value="statistics.courseCount || 0" />
            </el-col>
            <el-col :span="6">
              <el-statistic title="完成考试" :value="statistics.examCount || 0" />
            </el-col>
            <el-col :span="6">
              <el-statistic title="编程题目" :value="statistics.codingCount || 0" />
            </el-col>
            <el-col :span="6">
              <el-statistic title="学习时长" :value="statistics.studyHours || 0" suffix="小时" />
            </el-col>
          </el-row>
        </div>

        <!-- 操作日志 -->
        <div class="detail-section">
          <h3>最近操作</h3>
          <el-table :data="recentLogs" style="width: 100%">
            <el-table-column prop="action" label="操作" width="150" />
            <el-table-column prop="module" label="模块" width="120" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="ip" label="IP地址" width="120" />
            <el-table-column prop="createTime" label="操作时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.createTime) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getUserDetail, 
  getUserPermissions, 
  getUserStatistics, 
  getUserRecentLogs 
} from '@/api/user'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(true)
const userInfo = ref({})
const permissions = ref([])
const userPermissions = ref([])
const statistics = ref({})
const recentLogs = ref([])

// 获取用户详情
const loadUserDetail = async () => {
  try {
    const response = await getUserDetail(route.params.id)
    if (response.code === 200) {
      userInfo.value = response.data
    }
  } catch (error) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('获取用户详情失败')
  }
}

// 获取用户权限
const loadUserPermissions = async () => {
  try {
    const response = await getUserPermissions(route.params.id)
    if (response.code === 200) {
      permissions.value = response.data.permissions
      userPermissions.value = response.data.userPermissions
    }
  } catch (error) {
    console.error('获取用户权限失败:', error)
  }
}

// 获取用户统计
const loadUserStatistics = async () => {
  try {
    const response = await getUserStatistics(route.params.id)
    if (response.code === 200) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('获取用户统计失败:', error)
  }
}

// 获取最近操作日志
const loadRecentLogs = async () => {
  try {
    const response = await getUserRecentLogs(route.params.id, { limit: 10 })
    if (response.code === 200) {
      recentLogs.value = response.data
    }
  } catch (error) {
    console.error('获取操作日志失败:', error)
  }
}

// 编辑用户
const editUser = () => {
  router.push(`/user/user/edit/${route.params.id}`)
}

// 返回列表
const goBack = () => {
  router.push('/user/user')
}

// 工具函数
const getGenderText = (gender) => {
  const genderMap = {
    'MALE': '男',
    'FEMALE': '女',
    'UNKNOWN': '保密'
  }
  return genderMap[gender] || '未知'
}

const getUserTypeText = (userType) => {
  const typeMap = {
    'STUDENT': '学生',
    'TEACHER': '教师',
    'ADMIN': '管理员'
  }
  return typeMap[userType] || '未知'
}

const formatDate = (date) => {
  if (!date) return '未填写'
  return new Date(date).toLocaleDateString()
}

const formatDateTime = (datetime) => {
  if (!datetime) return '未知'
  return new Date(datetime).toLocaleString()
}

// 页面加载
onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([
      loadUserDetail(),
      loadUserPermissions(),
      loadUserStatistics(),
      loadRecentLogs()
    ])
  } finally {
    loading.value = false
  }
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-detail {
  .detail-section {
    margin-bottom: 32px;
    
    h3 {
      margin-bottom: 16px;
      color: #303133;
      border-bottom: 2px solid #409eff;
      padding-bottom: 8px;
    }
    
    h4 {
      margin: 16px 0 8px 0;
      color: #606266;
    }
  }
  
  .avatar-section {
    text-align: center;
    
    .user-status {
      margin-top: 12px;
    }
  }
  
  .roles-section {
    min-height: 40px;
  }
  
  .permissions-section {
    max-height: 300px;
    overflow-y: auto;
  }
  
  .bio-content {
    line-height: 1.6;
    white-space: pre-wrap;
  }
}
</style>
